# encoding: utf-8
# @File  : node.py
# @Author: shaoyun
# @Date  : 2025/05/11

from datetime import datetime
from typing import Optional, Dict, Any, List
from pydantic import BaseModel, Field, field_validator, ConfigDict
from app.models.node import NodeStatus as EnumNodeStatus


class NodeBase(BaseModel):
    """节点基本信息"""
    name: str
    host_ip: str  # 新增 host_ip 字段
    ip: str
    port: int
    is_master: bool = False
    description: Optional[str] = None


class NodeCreate(NodeBase):
    """创建节点的请求模型"""
    pass


class NodeUpdate(BaseModel):
    """更新节点的请求模型"""
    name: Optional[str] = None
    host_ip: Optional[str] = None  # 新增 host_ip 可选字段
    ip: Optional[str] = None
    port: Optional[int] = None
    status: Optional[str] = None
    cpu_usage: Optional[float] = None
    memory_usage: Optional[float] = None
    description: Optional[str] = None

    @field_validator('status')
    @classmethod
    def validate_status(cls,v):
        if v and v not in [status.value for status in EnumNodeStatus]:
            raise ValueError(f"Invalid status value: {v}")
        return v


class NodeInDB(NodeBase):
    """数据库中的节点模型"""
    id: str
    status: str
    cpu_usage: float = 0.0
    memory_usage: float = 0.0
    created_at: datetime
    updated_at: datetime
    last_heartbeat: Optional[datetime] = None

    model_config = ConfigDict(from_attributes=True)



# 在 NodeStatus 类中添加验证
class NodeStatus(BaseModel):
    """节点状态上报模型"""
    node_id: str
    cpu_usage: float
    memory_usage: float
    load_average: Optional[List[float]] = None
    disk_usage: Optional[Dict[str, float]] = None
    timestamp: int = Field(default_factory=lambda: int(datetime.utcnow().timestamp()))

    @field_validator('cpu_usage', 'memory_usage')
    @classmethod
    def validate_usage(cls, v):
        if v < 0 or v > 100:
            raise ValueError('Usage must be between 0 and 100')
        return v


class NodeWithTasks(NodeInDB):
    """包含任务的节点模型"""
    active_tasks: int = 0
    completed_tasks: int = 0
    total_tasks: int = 0


class NodeHeartbeat(BaseModel):
    """节点心跳数据模型"""
    node_id: str
    timestamp: int = Field(default_factory=lambda: int(datetime.utcnow().timestamp()))
